/**
    Common functions for initialization of mutex and condition variables
*/
#include "shm_common.h"
#include "channel.h"

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/shm.h>


// mutex
/**
    Initializes a posix mutex
    @param mutex- the mutex
*/
void mutex_init( pthread_mutex_t *mutex )
{
	pthread_mutexattr_t attr;
	int pshared;

	if( pthread_mutexattr_init( &attr ) != 0 ) {
		printf( "Error pthread_mutexattr_init(): %s\n", strerror(errno) );
	}
	if( pthread_mutexattr_setpshared( &attr, PTHREAD_PROCESS_SHARED ) != 0 ) {
		printf( "Error pthread_mutexattr_setpshared(): %s\n", strerror(errno) );
	}

	pthread_mutex_init( mutex, &attr );

	if( pthread_mutexattr_getpshared( &attr, &pshared) != 0 ) {
		printf( "Error pthread_mutexattr_getpshared(): %s\n", strerror(errno) );
	}
	if( pshared != PTHREAD_PROCESS_SHARED ) {
		printf( "Fuck, it's not shared... %d %d\n", pshared, PTHREAD_PROCESS_SHARED );
	}

	//pthread_mutexattr_destroy( &attr );
}

/**
    Initializes a posix condition variable
    @param cond - the condition variable
*/
void cond_init( pthread_cond_t *cond )
{
	pthread_condattr_t attr;
	int pshared;

	if( pthread_condattr_init( &attr ) != 0 ) {
		printf( "Error pthread_condattr_init(): %s\n", strerror(errno) );
	}
	if( pthread_condattr_setpshared( &attr, PTHREAD_PROCESS_SHARED ) != 0 ) {
		printf( "Error pthread_condattr_setpshared(): %s\n", strerror(errno) );
	}

	pthread_cond_init( cond, &attr );

	if( pthread_condattr_getpshared( &attr, &pshared) != 0 ) {
		printf( "Error pthread_condattr_getpshared(): %s\n", strerror(errno) );
	}
	if( pshared != PTHREAD_PROCESS_SHARED ) {
		printf( "Fuck, it's not shared... %d %d\n", pshared, PTHREAD_PROCESS_SHARED );
	}

	//pthread_condattr_destroy( &attr );
}



